<template>
  <el-dialog
    :title="title"
    :visible.sync="addOrUpdateVisible"
    :before-close="cancel"
  >
    <el-form
      :model="ruleForm"
      ref="ruleForm"
      :rules="rules"
      class="demo-ruleForm mt10 plr30"
    >
      <el-row :gutter="20">
        <el-col
          :span="24"
          v-if="
            title == '新增审批' || title == '修改审批' || title == '发起审批'
          "
        >
          <el-form-item label="审批模板" prop="classifyId">
            <el-select
              style="width: 100%"
              :disabled="
                title != '新增审批' &&
                title != '修改审批' &&
                title != '发起审批'
              "
              v-model="ruleForm.classifyId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.id + ''"
                :label="
                  item.classifyName +
                  (item.remark === null ? '' : '----' + item.remark)
                "
                :value="item.id + ''"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="审批标题" prop="title">
            <el-input
              :disabled="
                title != '新增审批' &&
                title != '修改审批' &&
                title != '发起审批'
              "
              v-model="ruleForm.title"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="审批内容" prop="content">
            <el-input
              :disabled="
                title != '新增审批' &&
                title != '修改审批' &&
                title != '发起审批'
              "
              type="textarea"
              :autosize="{ minRows: 6, maxRows: 10 }"
              placeholder="请输入内容"
              v-model="ruleForm.content"
              maxlength="255"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mt" v-if="ruleForm.id">
          <el-button type="primary" @click="details">审批内容</el-button>
        </el-col>
        <el-col :span="24" v-if="title == '审核审批'">
          <div>
            <el-radio
              v-model="radio"
              label="1"
              @change="ruleForm.approvalIdea = '已阅'"
              >已阅</el-radio
            >

            <el-radio
              v-model="radio"
              label="2"
              @change="ruleForm.approvalIdea = '予以通过'"
              >予以通过</el-radio
            >
          </div>
          <el-form-item label="审批意见" prop="approvalIdea">
            <el-input
              type="textarea"
              :autosize="{ minRows: 6, maxRows: 10 }"
              placeholder="请输入内容"
              v-model="ruleForm.approvalIdea"
              maxlength="255"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="附件" prop="signatureUrl">
            <FileUpload
              :limit="1"
              v-model="ruleForm.signatureUrl"
              :fileSize="200"
              :fileType="[]"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row type="flex" justify="center">
      <el-button
        type="primary"
        v-if="title == '发起审批' || title == '修改审批' || title == '新增审批'"
        @click="submit1($event)"
        >发起审批
      </el-button>
      <el-button
        type="primary"
        v-if="
          title == '修改审批' ||
          title == '流转审批' ||
          title == '发起审批' ||
          title == '新增审批'
        "
        @click="submit($event)"
        >确 定</el-button
      >
      <el-button type="primary" v-if="title == '审核审批'" @click="submit(201)"
        >保 存</el-button
      >
      <el-button type="primary" v-if="title == '审核审批'" @click="submit(301)"
        >通 过</el-button
      >
      <el-button type="danger" v-if="title == '审核审批'" @click="submit(302)"
        >驳 回</el-button
      >
      <el-button @click="cancel">取 消</el-button>
    </el-row>
    <!-- <addDialog ref="addDialog" @dialogBack="(e) => a1" /> -->
  </el-dialog>
</template>

<script>
import {
  approvalClassifyList, // 审批模板
  approvalFromQueryApprovalByLaunch, // 获取业务有没有新增过
  approvalFromAddFrom, // 新增审批
  approvalFromUpdateApproval, //修改审批
  approvalFromInitiateApproval, //发起审批
  approvalFromQueryFromById, // 获取审批表单详情信息 由我
  approvalFromQuerySubmitById, // 获取审批表单详情信息 待我
  approvalFromApproval, //待我审核审批
} from "@/api/system/Approval";
import { mapState } from "vuex";
// import { checkoutInfo, installId } from "@/api/IMS/purchase";
// import addDialog from "@/views/IMS/purchase/components/addDialog.vue"; //我是采购详情
export default {
  // components: { addDialog },
  computed: {
    ...mapState({
      user: (state) => state.user.user,
    }),
  },
  data() {
    return {
      addOrUpdateVisible: false,
      title: "新增审批",
      radio: "",
      ruleForm: {
        title: "",
        content: "",
        imgUrl: "",
        approvalIdea: "",
        approvalStaffId: "",
        approvalStaffName: "",
        fromId: "",
        classifyId: "",
        businessId: "",
        type: "",
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "change" }],
        // content: [{ required: true, message: '请输入内容', trigger: 'change' }],
        approvalIdea: [
          { required: true, message: "请输入审批意见", trigger: "change" },
        ],
        classifyId: [
          { required: true, message: "请选择审批模板", trigger: "change" },
        ],
      },
      options: [],
    };
  },
  methods: {
    a1() {
      console.log("我是关闭调用");
    },
    // 获取审批内容
    async details() {
      const obj = { ...this.ruleForm };
      const res1 = obj.hasOwnProperty("fromId")
        ? await approvalFromQueryFromById({ id: obj.fromId })
        : await approvalFromQueryFromById({ id: obj.id });

      const type = Number(res1.data.type);
      const businessId = res1.data.businessId;
      let url = "";

      switch (type) {
        case 1:
        case 2:
        case 3:
          url = "/IMS/purchase";
          break;
        case 5:
          url = "/lease/outDetil";
          break;
        case 6:
          url = "/lease/inDetail";
          break;
        case 7:
          url = "/lease/stopDetail";
          break;
        case 8:
          url = "/lease/addDetail";
          break;
        default:
          url = "";
      }

      if ([5, 6, 7, 8].includes(type)) {
        this.$router.push({
          path: url,
          query: { id: businessId },
        });
      } 
    },

    // id 是当前数据id  type 是审批类型  businessId 是业务id type1 是业务类型  show是否由我发起
    async init(id, type, businessId, type1, show) {
      try {
        // 获取审批分类列表
        const res = await approvalClassifyList({
          pageIndex: 1,
          pageSize: 100,
          type: type1,
        });
        this.options = res.data.records;

        // 如果提供了 businessId 和 type1，则设置它们
        if (businessId) {
          this.ruleForm.businessId = businessId;
          this.ruleForm.type = type1;
        }

        // 根据 id 和 type 决定标题和获取数据
        if (!businessId) {
          if (id) {
            this.setTitleByType(type);
            if (type === 0 || type == 1) {
              const res = await approvalFromQueryFromById({ id });
              this.ruleForm = res.data;
            }
            if (type == 2) {
              const res = await approvalFromQuerySubmitById({ id });
              this.ruleForm = res.data;
            }
          } else {
            this.title = "新增审批";
          }
        } else if (!id) {
          const res1 = await approvalFromQueryApprovalByLaunch({
            pageIndex: 1,
            pageSize: 20,
            userId: this.user.userId,
            businessId,
          });

          const records = res1.data.records;
          if (records.length > 0 && records[0].status === 101) {
            this.title = "修改审批";
            const detailRes = await approvalFromQueryFromById({
              id: records[0].id,
            });
            this.ruleForm = detailRes.data;
          } else {
            this.title = "新增审批";
          }
        }

        this.addOrUpdateVisible = true;
      } catch (err) {
        console.error(err);
      }
    },
    // 根据类型设置标题
    setTitleByType(type) {
      switch (type) {
        case 1:
          this.title = "发起审批";
          break;
        case 2:
          this.title = "审核审批";
          break;
        case 3:
          this.title = "流转审批";
          break;
        case 4:
        case 5:
          this.title = "查看审批";
          break;
        default:
          this.title = "修改审批";
          break;
      }
    },
    async submit(type) {
      await this.$refs.ruleForm.validate();
      let obj = JSON.parse(JSON.stringify(this.ruleForm));
      try {
        //  this.title == "新增审批"
        if (this.title == "新增审批") {
          await approvalFromAddFrom(obj);
          this.$modal.msgSuccess(`新增成功`);
        } else if (this.title == "修改审批") {
          await approvalFromUpdateApproval(obj);
          this.$modal.msgSuccess(`修改成功`);
        } else {
          let obj1 = {
            id: this.ruleForm.id,
            approvalStatus: type,
            approvalIdea: this.ruleForm.approvalIdea,
            signatureUrl: this.ruleForm.signatureUrl,
          };
          await approvalFromApproval(obj1);
          if (type == 201) this.$modal.msgSuccess(`保存成功`);
          if (type == 301) this.$modal.msgSuccess(`通过成功`);
          if (type == 302) this.$modal.msgSuccess(`驳回成功`);
        }
        this.cancel(true);
      } catch (err) {
        console.log(err);
      }
    },
    async submit1(el, type) {
      await this.$refs.ruleForm.validate();
      let obj = JSON.parse(JSON.stringify(this.ruleForm));
      try {
        await approvalFromInitiateApproval(obj);
        this.cancel(true);
        this.$modal.msgSuccess(`发起成功`);
      } catch (err) {
        console.log(err);
      }
    },
    cancel(e) {
      this.ruleForm = {
        title: "",
        content: "",
        imgUrl: "",
        approvalIdea: "",
        approvalStaffId: "",
        approvalStaffName: "",
        fromId: "",
        classifyId: "",
      };
      this.radio = "";
      console.log(e);
      e ? this.$emit("dialogBack") : "";
      this.$refs["ruleForm"].resetFields();
      this.addOrUpdateVisible = false;
    },
  },
};
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  border-bottom: 1px solid #e9e9e9;
}

/deep/ .el-form--label-top .el-form-item__label {
  padding: 0 0;
}
.image-slot {
  line-height: 80px;
}
.mt {
  margin-bottom: 20px;
}
</style>
